<?php
/**
 * Created by PhpStorm.
 * User: lelouchms
 * Date: 2019/3/22
 * Time: 4:18
 */

namespace app\common\library;


use app\common\exception\LoginException;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;

class JWTToken
{

    private static $secret = "house_jsoiGJjaof43AJfg";

    public static function getToken($id, $module)
    {
        $signer = new Sha256();
        return (new Builder())
            ->setIssuer("http://$module.pay")
            ->setAudience("http://$module.pay")
            ->setId(uniqid($module . $id), true)
            ->setIssuedAt(time())
            ->setExpiration(bcadd((86400 * 30), time()))
            ->set('user_id', $id)
            ->set("module", $module)
            ->sign($signer, self::$secret)
            ->getToken();
    }

    public static function parse($token, $module)
    {
        if (empty($token)) throw new LoginException(LoginException::LOGIN_NONE);
        $parse = (new Parser())
            ->parse((string)$token);
        $signer = new Sha256();
        $flag = $parse->verify($signer, self::$secret);
        if ($flag === false) throw new LoginException(LoginException::LOGIN_NONE);
        if ($parse->getClaim("module") !== $module) throw new LoginException(LoginException::LOGIN_NONE);
        return $parse->getClaims();
    }


}